﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace HelloWorldDemo.Common
{
    public class WatermarkedTextBox : TextBox
    {
        public static readonly DependencyProperty DefaultTextProperty = DependencyProperty.Register("DefaultText", typeof(string), typeof(WatermarkedTextBox), new PropertyMetadata(""));
        public event EventHandler WatermarkedTextChanged;

        public WatermarkedTextBox()
        {
            base.TextChanged += new TextChangedEventHandler(this.OnWotermarkedTextBoxTextChanged);
        }

        public override void OnApplyTemplate()
        {
            base.Text = this.DefaultText;
            base.OnApplyTemplate();
        }

        protected override void OnGotFocus(RoutedEventArgs e)
        {
            if (string.Equals(base.Text, this.DefaultText, StringComparison.OrdinalIgnoreCase))
            {
                base.Text = string.Empty;
            }
            base.OnGotFocus(e);
        }

        protected override void OnLostFocus(RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(base.Text))
            {
                base.Text = this.DefaultText;
            }
            base.OnLostFocus(e);
        }

        private void OnWotermarkedTextBoxTextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.Equals(base.Text, this.DefaultText, StringComparison.OrdinalIgnoreCase))
            {
                if (this.WatermarkedTextChanged != null)
                    this.WatermarkedTextChanged(this, e);
            }
        }

        public string DefaultText
        {
            get
            {
                return (string)base.GetValue(DefaultTextProperty);
            }
            set
            {
                base.SetValue(DefaultTextProperty, value);
            }
        }
    }

}

